﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using BLL;
using Model;
using System.Linq;
using System.Data.SqlClient;

namespace WebPortal.Controllers
{
    public class ODSConfigController : BaseController
    {
        public ActionResult ODSConfigAdd()
        {
            return View();
        }
        public ActionResult SourceList()
        {
            return View();
        }
        public ActionResult TableInfo()
        {
            return View();
        }
        public ActionResult CheckUpdate(string odsid, bool update, string dbName)
        {
            if (update)
            {
                LoginInfo loginInfos = base.loginInfo();
                loginInfos.DBName = dbName;
                ModelConfigBLL mbll = new ModelConfigBLL(loginInfos);
                ModelConfig model = mbll.GetItem(odsid);
                if (model.AddType == "Reference")
                {
                    odsid = model.ParentModelID;
                }
                SqlParameter[] pare = new SqlParameter[]{   
                new SqlParameter("@ModelID",odsid),  
                new SqlParameter("@Rows",10),
                new SqlParameter("@PageNum",1)
                };

                IList<ModelConfig> list = mbll.GetRefModelList(pare, "CreateTime", "desc");
                if (list.Count > 0)
                    return Json(odsid);
                else
                    return Json("1");
            }
            else
                return Json("1");
        }
        /// <summary>
        /// 添加的代码
        /// </summary>
        /// <param name="odsid"></param>
        /// <param name="stgingdbTables"></param>
        /// <param name="onDataGridData"></param>
        /// <param name="tableCnName"></param>
        /// <param name="tableEnName"></param>
        /// <param name="tableInfo"></param>
        /// <param name="dbName"></param>
        /// <returns></returns>
        public ActionResult InsertItem(string odsid, string stgingdbTables, string onDataGridData, string dbName)
        {
            string nmID = Request.Params["nmID"];
            string ndbName = Request.Params["ndbName"];
            string modelid = odsid;
            LoginInfo loginInfos = base.loginInfo();
            if (string.IsNullOrEmpty(nmID))
                loginInfos.DBName = dbName;
            else//发送到实例页面请求
            {
                loginInfos.DBName = ndbName;
                odsid = nmID;
            }
            ModelConfigBLL mbll = new ModelConfigBLL(loginInfos);
            StagingdbTableBLL stgbll = new StagingdbTableBLL(loginInfos);
            ModelConfig model = mbll.GetItem(odsid);
            List<string> msg = new List<string>();
            if (model.AddType == "Reference")//引用模型
            {
                odsid = model.ParentModelID;
            }

            ODSConfigTransData data = new ODSConfigTransData();
            data.ODSConfig = new ODSConfig();
            data.ODSConfig.GUID = odsid;
            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            //解析页面源表参数
            IList<ODSSTGConfig> item2 = new List<ODSSTGConfig>();
            IList<Staging_dbTable> tableList = (IList<Staging_dbTable>)jsSerializer.Deserialize(stgingdbTables, typeof(IList<Staging_dbTable>));
            foreach (Staging_dbTable item in tableList)
            {
                item2.Add(new ODSSTGConfig()
                {
                    StgID = item.GUID,
                    STG_TB_Schema = "Staging_db",
                    STG_TB_Name = item.ViewName,
                    STG_DisplayName = item.DisplayName,
                    SourceSysName = item.SourceSysName
                });
            }
            data.ODSSTGConfigList = item2;
            //解析页面关联条件值
            if (!string.IsNullOrEmpty(onDataGridData))
            {
                onDataGridData = onDataGridData.Replace(",]", "]");
                data.ODSSTGConfigTransDataList = (IList<ODSSTGConfigTransData>)jsSerializer.Deserialize(onDataGridData, typeof(IList<ODSSTGConfigTransData>));
            }
            else
            {
                data.ODSSTGConfigTransDataList = new List<ODSSTGConfigTransData>();
            }

            ODSConfigBLL bll = new ODSConfigBLL(loginInfos);
            try
            {
                #region 变更源表后，清除后面dq，模型配置
                //SqlParameter[] pare = new SqlParameter[]{
                //new SqlParameter("@modelID",odsid) 
                //};
                //List<Staging_dbTable> stglist = (List<Staging_dbTable>)stgbll.GetStging_dbInfo(pare);//保存的ods配置
                //if (stglist.Count > 0)
                //{
                //    if (tableList.Count != stglist.Count)
                //    {
                //        bll.InitDQAndModel(odsid);// 清除配置
                //    }
                //    else
                //    {
                //        bool change = false;
                //        foreach (Staging_dbTable stb in tableList)
                //        {
                //            if (!stglist.Exists(o => { return o.ViewName == stb.ViewName; }))
                //            {
                //                change = true;
                //                break;
                //            }
                //        }
                //        if (change)//ods表已经变更
                //        {
                //            bll.InitDQAndModel(odsid);// 清除配置
                //        }
                //    }
                //}
                #endregion
                SqlParameter[] pare = new SqlParameter[]{
                    new SqlParameter("@modelID",odsid) 
                };
                IList<Staging_dbTable> oldlist = stgbll.GetStging_dbInfo(pare);//原数据源表列表

                bool rz = bll.Update(data);//提交更新
                if (rz)
                {
                    //如果添加源表，添加自动生成数据质量主键唯一约束
                    if (oldlist.Count > 0)//更新时进入操作
                    {
                        foreach (Staging_dbTable ostg in tableList)
                        {
                            Staging_dbTable findStg = oldlist.FirstOrDefault(o => { return o.SourceSystemID == ostg.SourceSystemID && o.ViewName == ostg.ViewName; });
                            if (findStg == null)
                            {
                                bll.AddAutoDQ(ostg, odsid);//添加自动生成数据质量主键唯一约束
                            }
                        }
                    }

                    if (!string.IsNullOrEmpty(nmID))//发送模型配置时导入源模型dq配置
                    {
                        DQConfigBLL dqbll = new DQConfigBLL(loginInfos);
                        dqbll.SendDQConfig(modelid, dbName, nmID, ndbName);
                    }
                    msg.Add("1");
                }
                else
                    msg.Add("0");
                return Json(msg);
            }
            catch (Exception ex) { return Json(ex.Message); }

        }
        /// <summary>
        /// Stging_db表集合
        /// </summary>
        /// <param name="dbName"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        public ActionResult GetStging_dbTbList()
        {
            string tableName = Request.Params["tableName"];
            string sourceSysName = Request.Params["sourceSysName"];
            string tarSysID = Request.Params["tarSysID"];
            string viewID = Request.Params["viewID"];
            string dbName = Request.Params["dbName"];

            string order = Request.Params["order"];
            string sort = Request.Params["sort"];
            string rows = Request.Params["rows"];
            string page = Request.Params["page"];
            string expIDs = Request.Params["ExpIDs"];
            if (string.IsNullOrEmpty(expIDs))
                expIDs = "";
            if (string.IsNullOrEmpty(sort))
                sort = "SourceSysName";
            if (!string.IsNullOrEmpty(tableName))
                tableName = tableName.Replace("[", "").Replace("]", "");
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            StagingdbTableBLL bll = new StagingdbTableBLL(loginInfos);

            SqlParameter[] pare = new SqlParameter[]{
            new SqlParameter("@TableName",tableName), 
            new SqlParameter("@SourceSysName",sourceSysName),   
            new SqlParameter("@TarSysID",tarSysID),  
            new SqlParameter("@ExpIDs",expIDs),   
            new SqlParameter("@viewID",viewID??""), 
            new SqlParameter("@Order",order),
            new SqlParameter("@Sort",sort),
            new SqlParameter("@Rows",rows),
            new SqlParameter("@PageNum",page)
            };

            IList<Staging_dbTable> list = bll.GetList(pare);

            int count = 0;
            if (list.Count > 0)
                count = list[0].Count;
            Dictionary<String, Object> jsonDict = new Dictionary<String, Object>();
            jsonDict.Add("total", count);
            jsonDict.Add("rows", list);

            return Json(jsonDict);
        }

        /// <summary>
        /// 查询Stging_db表 
        /// </summary>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public ActionResult GetTableInfo(string tableName, string modelID, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            string version = Request.Params["version"];
            TableInfoBLL bll = new TableInfoBLL(loginInfos);
            Dictionary<String, Object> jsonDict = new Dictionary<String, Object>();
            jsonDict.Add("total", 1);
            if (!string.IsNullOrEmpty(tableName))
            {
                jsonDict.Add("rows", bll.GetStagingTableInfo("Staging_db", tableName));
            }
            if (!string.IsNullOrEmpty(modelID))
            {
                IList<ModelViewConfig> mvList = bll.GetModelViewInfo(modelID, version);

                List<TableInfo> tbList = new List<TableInfo>();

                foreach (ModelViewConfig item in mvList)
                {
                    TableInfo _temp = new TableInfo
                    {
                        GUID = item.GUID,
                        ColumnName = item.ColumnName,
                        Desc = item.ColumnDescription,
                        ColumnType = item.ColumnType,
                        ColumnTypeSource = item.ColumnType,
                        Length = item.ColumnLength,
                        Precision = item.ColumnPrecision,
                        DecimalPlaces = item.ColumnScale,
                        PK = item.ColumnIsBusinessPK.ToString(),
                        IsNull = item.ColumnIsNullable.Trim(),
                        DefaultValue = item.ColumnDefaultValue
                    };
                    tbList.Add(_temp);
                }
                jsonDict.Add("rows", tbList);
            }
            return Json(jsonDict);
        }
        /// <summary>
        /// 获取整合条件
        /// </summary>
        /// <param name="modelID"></param>
        /// <param name="dbName"></param>
        /// <returns></returns>
        public ActionResult GetOnInfo(string modelID, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ODSConfigBLL bll = new ODSConfigBLL(loginInfos);
            ModelConfigBLL mbll = new ModelConfigBLL(loginInfos);
            ModelConfig model = mbll.GetItem(modelID);
            if (model.AddType == "Reference")
                modelID = model.ParentModelID;
            ODSConfigTransData data = bll.GetItem(modelID);

            Dictionary<String, Object> jsonDict = new Dictionary<String, Object>();
            jsonDict.Add("total", 1);
            jsonDict.Add("rows", data.ODSSTGConfigTransDataList);

            return Json(jsonDict);
        }

        public ActionResult GetStging_dbInfo(string modelID, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            StagingdbTableBLL bll = new StagingdbTableBLL(loginInfos);

            ModelConfigBLL mbll = new ModelConfigBLL(loginInfos);
            ModelConfig model = mbll.GetItem(modelID);
            if (model.AddType == "Reference")
                modelID = model.ParentModelID;

            SqlParameter[] pare = new SqlParameter[]{
            new SqlParameter("@modelID",modelID) 
            };
            IList<Staging_dbTable> list = bll.GetStging_dbInfo(pare);

            Dictionary<String, Object> jsonDict = new Dictionary<String, Object>();
            jsonDict.Add("total", 0);
            jsonDict.Add("rows", list);

            return Json(jsonDict);
        }

        public ActionResult GetChecked(string guid, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            StagingdbTableBLL bll = new StagingdbTableBLL(loginInfos);
            return Json(bll.GetODSStgTabs(guid));
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        public ActionResult List(string tableName, string dbName, int pageSize = 10, int pageIndex = 1)
        {
            pageSize = int.Parse(Request.Params["rows"]);
            pageIndex = int.Parse(Request.Params["page"]);

            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ODSConfigBLL bll = new ODSConfigBLL(loginInfos);
            IList<ODSConfig> list = bll.GetList(tableName, pageSize, pageIndex);
            int count = bll.GetListCount(tableName);

            Dictionary<String, Object> jsonDict = new Dictionary<String, Object>();
            jsonDict.Add("total", count);
            jsonDict.Add("rows", list);

            return Json(jsonDict);
        }

        /// <summary>
        /// 查询Stging_db表的列
        /// </summary>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public ActionResult SyncTableColumns(string tableName, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            TableInfoBLL bll = new TableInfoBLL(loginInfos);
            List<string> result = bll.GetTableColumns("Staging_db." + tableName);
            result.Remove(result.Where(p => p.Equals("DB_ID")).FirstOrDefault());
            return Json(result);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int DeleteItem(string id, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ODSConfigBLL bll = new ODSConfigBLL(loginInfos);
            return bll.Delete(id);
        }

        /// <summary>
        /// 检查名称是否存在
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="odsid"></param>
        /// <returns></returns>
        public ActionResult ODSTableNameIsExist(string tableName, string odsid, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ODSConfigBLL bll = new ODSConfigBLL(loginInfos);
            return Content(bll.ODSTableNameIsExist(tableName, odsid) ? "1" : "0");
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult ODSConfigEdit(string id, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ODSConfigBLL bll = new ODSConfigBLL(loginInfos);
            ViewData["pageNumber"] = GetPageIndex(id, 15, dbName);
            return View(bll.GetItem(id));
        }

        public int GetPageIndex(string guid, int pageSize, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            StagingdbTableBLL bll = new StagingdbTableBLL(loginInfos);
            return bll.GetPageIndex(guid, pageSize);
        }

        public ActionResult GetODSTableNameList(string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ODSConfigBLL bll = new ODSConfigBLL(loginInfos);
            return Json(bll.GetODSTableNameList());
        }
    }
}
